// 接口服务器基地址
const baseURL = 'https://pcapi-xiaotuxian-front-devtest.itheima.net'

import { useMemberStore } from '@/store/member'

uni.addInterceptor('request',{
  invoke(args){
    if(!(args.url as string).startsWith('http') ){
      args.url = baseURL + args.url
    }

    args.header = {
      ...args.header,
      'source-client':'miniapp'
    }

    const store = useMemberStore()

    const token = store.profile.token
    if(token){
      args.header.Authorization = token
    }
  }
})


uni.addInterceptor('uploadFile',{
  invoke(args){
    if(!(args.url as string).startsWith('http') ){
      args.url = baseURL + args.url
    }

    args.header = {
      ...args.header,
      'source-client':'miniapp'
    }

    const store = useMemberStore()

    const token = store.profile.token
    if(token){
      args.header.Authorization = token
    }
  }
})

type ApiRes = {
  code:string,
  msg:string,
  result:any
}

// 封装一个通用的http请求
export const http = <T>(options:UniApp.RequestOptions) =>{
  return new Promise<T>((resolve, reject) => {
    uni.request({
      ...options,
      success(res){
        if(res.statusCode >= 200 && res.statusCode <= 300){
          resolve((res.data as ApiRes).result)
        }else{
          uni.showToast({
            icon:'none',
            title: (res.data as AnyObject).message
          })
          reject(res)
        }
 
      },
      fail(err){
       reject(err)
      }
    })
  })
}
